TripDetails = {

    saveTrip : function()
    {
      $.ajax({
          url : "/copytrip",
          data : {
            trip : $("#tripId").val(),
          },
          success : function(data)
          {
            data = $.parseJSON(data);
            location = "/edit.jsp?trip=" + data.newTripID;
          },
          type : "POST"
      });
    },

    changeTrip : function()
    {
      $("#tripId").val($(this).val());
      TripDetails.loadTrip();
    },

    loadTrip : function()
    {
      if ($("#tripId").val() != "")
      {
        $.ajax({
                url : "/loadtrip",
                data : {
                  trip : $("#tripId").val()
                },
                success : function(data)
                {
                  data = $.parseJSON(data);
                  $("#tripName").val(data.name);
                  $("#tripDescription").val(data.description);

                  $("#waypointList").empty();
                  for (i in data.destinations)
                  {
                    $("#waypointList").append(
                        "<li><img class='vmid' src='img/icons/pin.png'><span>"
                            + data.destinations[i].name + "</span></li>");
                  }
                  if (data.mine)
                  {
                    $("#saveTrip").hide();
                    $("#editTrip").show();
                  }
                  else
                  {
                    $("#saveTrip").show();
                    $("#editTrip").hide();
                    if($("#tripPicker option[value='"+$("#tripId").val()+"']").length == 0)
                    $("#tripPicker").prepend(
                        "<option value='" + $("#tripId").val() + "'>"
                            + data.name + "</option>");
                    $("#tripPicker").val($("#tripId").val());
                  }
                  var mapdata = {};
                  if (data.destinations[0])
                    mapdata.start = data.destinations[0].name;
                  if (data.destinations.length > 1)
                    mapdata.end = data.destinations[data.destinations.length - 1].name;
                  mapdata.waypoints = [];
                  for ( var i = 1; i < data.destinations.length - 1; i++)
                    mapdata.waypoints.push({
                        location : data.destinations[i].name,
                        stopover : true
                    });
                  Maps.buildMap(mapdata);
                },
                type : "POST"
            });
      }
    }

}

$(function()
{

  $("#tripPicker").change(TripDetails.changeTrip);

  if ($("#tripId").val() == "")
  {
    $("#tripPicker").change();
  }

  $("#saveTrip").click(TripDetails.saveTrip);

  $("#editTrip").click(function()
  {
    location = "/edit.jsp?trip=" + $("#tripId").val();
  });

  TripDetails.loadTrip()

});
